package com.project.chat.service;

import com.project.chat.pojo.ChiHuiTool;
import com.project.chat.pojo.Person;
import com.project.chat.pojo.Room;
import com.project.chat.pojo.SettingTool;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class GameService {

    private static final Map<Integer, Room> ROOMS = new HashMap<>(); //房间列表
    private static final int ROOM_NUM_MIN = 3;

    private static int roomId = 0; //房间编号
    public static ChiHuiTool chiHuiTool = ChiHuiTool.createChiHuiTool(); //词汇器

    //查看某一房间 房间号
    public Room getRoom(int id){
        return ROOMS.get(id);
    }

    //创建房间 需要规则 返回房间号
    public int createRoom(SettingTool settingTool) throws IndexOutOfBoundsException{

        int num = settingTool.getPmNum() + settingTool.getWdNum();
        //至少三个人
        if(num < ROOM_NUM_MIN) throw new IndexOutOfBoundsException("房间人数范围错误");
        //创建房间
        Room room = new Room(roomId, num, settingTool);
        ROOMS.put(roomId, room);
        System.out.println("房间创建成功!\n房间号为: "+roomId+" \n====房间信息==== \n"
                +"房间人数为："+room.getNum() + " 房间当前人数为："+room.getNow_num()
                +"\n房间人员列表："+ room.getPersons().toString()+"\n房间设置： 词汇号："
                +room.getSetting().getChiHuiId() + " 平民数："+room.getSetting().getPmNum()
                +" 卧底数："+ room.getSetting().getWdNum());
        return roomId++;
    }

    //加入房间并改变房间状态
    public boolean joinRoom(int id, String username){

        Room room = getRoom(id);
        if(room == null) return false; //无该房间

        return room.addPerson(new Person(username));
    }

    //删除房间-结束游戏
    public void deleteRoom(Integer id){
        if(id != null){
            Room room = getRoom(id);
            if(room != null) {
                room.clearRoom(); //清空房间信息
                ROOMS.remove(id); //移除房间
            }
        }else{
            //移除所有房间
            ROOMS.clear();
        }

    }

    //退出房间
    public void exitRoom(String username, int id){
        Room room = getRoom(id);
        if(room == null) return;

        room.deletePerson(username);
    }

}
